const mysql = require('mysql2/promise');

// 数据库连接配置 - 从环境变量获取，如果没有则使用默认值
const dbConfig = {
    host: process.env.DB_HOST || '43.143.253.188',
    port: parseInt(process.env.DB_PORT) || 3306,
    user: process.env.DB_USER || 'nextjs',
    password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
    database: process.env.DB_NAME || 'nextjs'
};

async function removeAllForeignKeys() {
    let connection;
    
    try {
        console.log('🔌 连接到数据库...');
        console.log(`主机: ${dbConfig.host}:${dbConfig.port}`);
        console.log(`数据库: ${dbConfig.database}`);
        console.log(`用户: ${dbConfig.user}`);
        
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！\n');
        
        // 获取所有表名
        console.log('📋 获取数据库表列表...');
        const [tables] = await connection.execute('SHOW TABLES');
        const tableNames = tables.map(row => Object.values(row)[0]);
        console.log(`找到 ${tableNames.length} 个表:\n`);
        
        // 存储所有外键信息
        const allForeignKeys = [];
        
        // 遍历每个表，查找外键约束
        for (const tableName of tableNames) {
            console.log(`🔍 检查表: ${tableName}`);
            
            try {
                // 获取表的创建语句
                const [createTableResult] = await connection.execute(`SHOW CREATE TABLE \`${tableName}\``);
                const createTableSql = createTableResult[0]['Create Table'];
                
                // 查找外键约束
                const foreignKeyMatches = createTableSql.match(/CONSTRAINT\s+`([^`]+)`\s+FOREIGN KEY\s*\(`([^`]+)`\)\s+REFERENCES\s+`([^`]+)`\s*\(`([^`]+)`\)/gi);
                
                if (foreignKeyMatches && foreignKeyMatches.length > 0) {
                    console.log(`  ⚠️  发现 ${foreignKeyMatches.length} 个外键约束:`);
                    
                    for (const match of foreignKeyMatches) {
                        // 提取约束名称
                        const constraintNameMatch = match.match(/CONSTRAINT\s+`([^`]+)`/i);
                        if (constraintNameMatch) {
                            const constraintName = constraintNameMatch[1];
                            allForeignKeys.push({
                                table: tableName,
                                constraint: constraintName
                            });
                            console.log(`    - 约束名: ${constraintName}`);
                        }
                    }
                } else {
                    console.log(`  ✅ 无外键约束`);
                }
                
            } catch (error) {
                console.log(`  ❌ 检查表 ${tableName} 时出错: ${error.message}`);
            }
        }
        
        console.log(`\n📊 外键约束统计:`);
        console.log(`总共发现 ${allForeignKeys.length} 个外键约束\n`);
        
        if (allForeignKeys.length === 0) {
            console.log('🎉 数据库中没有外键约束，无需操作！');
            return;
        }
        
        // 询问是否继续
        console.log('⚠️  即将删除所有外键约束，此操作不可逆！');
        console.log('按 Ctrl+C 取消，或等待 5 秒后自动继续...');
        
        // 等待5秒
        await new Promise(resolve => setTimeout(resolve, 5000));
        
        // 开始删除外键约束
        console.log('\n🗑️  开始删除外键约束...\n');
        
        let successCount = 0;
        let errorCount = 0;
        
        for (const fk of allForeignKeys) {
            try {
                console.log(`正在删除表 ${fk.table} 中的约束 ${fk.constraint}...`);
                
                // 删除外键约束
                await connection.execute(`ALTER TABLE \`${fk.table}\` DROP FOREIGN KEY \`${fk.constraint}\``);
                
                console.log(`  ✅ 成功删除约束 ${fk.constraint}`);
                successCount++;
                
            } catch (error) {
                console.log(`  ❌ 删除约束 ${fk.constraint} 失败: ${error.message}`);
                errorCount++;
            }
        }
        
        console.log('\n📊 删除结果统计:');
        console.log(`✅ 成功: ${successCount}`);
        console.log(`❌ 失败: ${errorCount}`);
        console.log(`📋 总计: ${allForeignKeys.length}`);
        
        if (successCount > 0) {
            console.log('\n🎉 外键约束删除完成！');
            console.log('💡 建议: 在生产环境中，请确保应用程序逻辑能够处理数据完整性检查。');
        }
        
    } catch (error) {
        console.error('❌ 操作失败:', error.message);
        if (error.code) {
            console.error('错误代码:', error.code);
        }
    } finally {
        if (connection) {
            await connection.end();
            console.log('\n🔌 数据库连接已关闭');
        }
    }
}

// 显示环境变量信息
console.log('🌍 环境变量信息:');
console.log(`DB_HOST: ${process.env.DB_HOST || '未设置 (使用默认值)'}`);
console.log(`DB_PORT: ${process.env.DB_PORT || '未设置 (使用默认值)'}`);
console.log(`DB_USER: ${process.env.DB_USER || '未设置 (使用默认值)'}`);
console.log(`DB_PASS: ${process.env.DB_PASS ? '***已设置***' : '未设置 (使用默认值)'}`);
console.log(`DB_NAME: ${process.env.DB_NAME || '未设置 (使用默认值)'}`);
console.log('');

// 运行主函数
removeAllForeignKeys().catch(console.error); 